import re
import pandas as pd
from tkinter import filedialog
import tkinter as tk

def select_input_file_path():
    root = tk.Tk()
    root.withdraw()
    file_path = filedialog.askopenfilename(
        title="选择txt输入文件位置",
        defaultextension=".txt",
        filetypes=[("txt files", "*.txt"), ("All files", "*.*")],
    )
    return file_path


def select_output_file_path():
    root = tk.Tk()
    root.withdraw()
    file_path = filedialog.asksaveasfilename(
        title="选择excel文件保存位置",
        defaultextension=".xlsx",
        filetypes=[("xlsx files", "*.xlsx"), ("All files", "*.*")],
    )
    return file_path

# 定义关键字变量
KEYWORD = "58A1"  # 可以在这里修改关键字

# 输入和输出文件位置
filename = select_input_file_path()
excel_filename = select_output_file_path()
# 初始化一个空列表，用于存储分割后的内容块
blocks = []
# 初始化一个空字符串，用于临时存储当前内容块的内容
current_block = ""

# 正则表达式模式，用于匹配时间戳格式 [HH:MM:SS.mmm]
timestamp_pattern = re.compile(r'\[(\d{2}:\d{2}:\d{2}\.\d{3})\]')
del_pattern = re.compile(rf'^.*?(?=0x{KEYWORD})')
del_pattern_2 = re.compile(r'(\[\d+,\d+\]).*')
correct_pattern = re.compile(
    r'^\[\d{2}:\d{2}:\d{2}\.\d{3}\]'  # 时间戳
    rf'0x{KEYWORD}'                # 严格匹配4位十六进制数
    r'\[-?\d+,-?\d+,-?\d+\]'         # 一组整数
    r'='                              # 等号
    r'\[\d+,\d+\]$'                  # 整数对
)

excel_pattern = re.compile(
    r'^\[(\d{2}:\d{2}:\d{2}\.\d{3})\]'  # 时间戳
    r'0x([0-9a-fA-F]+)'                # 十六进制数
    r'.*?'                              # 忽略中间部分
    r'=\[(\d+),.*?\]$'                 # 等号后面的第一个整数
)


# 使用with语句打开文件，确保文件在使用后能被正确关闭
with open(filename, 'r', encoding='GB2312') as file:
    for line in file:
        # 去除行尾的换行符和空白字符
        cleaned_line = line.replace('收←◆', '')
        stripped_line = cleaned_line.strip()
        # 判断当前行是否为空行
        if stripped_line == "":
            # 如果当前内容块不为空，则将其添加到blocks列表中
            if current_block:
            # 保留一个时间戳 并删除多余内容
                # print(current_block)
                match = timestamp_pattern.search(current_block)
                if match:
                    first_timestamp = match.group(0)
                else:
                    first_timestamp = '[00:00:00.000]'
                current_block = timestamp_pattern.sub('', current_block)
                current_block = del_pattern.sub('', current_block)
                # current_block = current_block.replace("AT+CPOWD", "")
                current_block = del_pattern_2.sub(r'\1', current_block)
                current_block = first_timestamp + current_block
                # print(current_block)


            # 判断内容是否符合对应的正则表达式，符合加入，不符合去除
                if correct_pattern.match(current_block):
                    # print(current_block)
                    blocks.append(current_block)
            # 重置当前内容块为空字符串，为下一个内容块的读取做准备
            current_block = ""
        else:
            # 如果当前行不是空行，则将其添加到当前内容块中
            # 不希望保留换行符，在添加到current_block之前将其去除
            current_block += stripped_line

# 如果文件的最后一个内容块不是以空行结尾，则它也会被添加到blocks列表中
# 因为在for循环结束后，我们不会再有机会检查current_block是否为空
if current_block:
    # 保留一个时间戳 并删除多余内容
    match = timestamp_pattern.search(current_block)
    first_timestamp = match.group(0)
    current_block = timestamp_pattern.sub('', current_block)
    current_block = del_pattern.sub('', current_block)
    current_block = first_timestamp + current_block
    blocks.append(current_block)

# 创建一个空的列表来收集匹配的数据
data = []

# 遍历 blocks 列表
for block in blocks:
    # print(block)
    match = excel_pattern.match(block)
    print(match)
    if match:
        timestamp = match.group(1)
        hex_number = match.group(2)
        first_integer = int(match.group(3))
        # 将匹配的数据作为一行添加到列表中
        data.append([timestamp, hex_number, first_integer])
 
# 检查是否收集到了数据
if data:
    # 创建 DataFrame
    df = pd.DataFrame(data, columns=['Timestamp', 'Hex Number', 'First Integer'])
    
    # 计算 First Integer 列的平均值
    average_first_integer = df['First Integer'].mean()
    # 计算 First Integer 列的最大值和最小值
    max_first_integer = df['First Integer'].max()
    min_first_integer = df['First Integer'].min()
    
    print(f"平均值: {average_first_integer}")
    print(f"最大值: {max_first_integer}")
    print(f"最小值: {min_first_integer}")
    
    # 将平均值添加到 DataFrame 的最后一行
    df.loc['Average'] = ['', '', average_first_integer]
    df.loc['Max'] = ['', '', max_first_integer]
    df.loc['Min'] = ['', '', min_first_integer]    
    # 导出到 Excel
    df.to_excel(excel_filename, index=False)
    print(f"数据已成功导出到'{excel_filename}'文件中。")
else:
    print("没有匹配到任何数据。")